<template>
  <editTemplateDialog
    class="editTemplateDialog"
      :dialogInfo="editTemplateDialogInfo"
      @baseMounted="baseMounted"
      :self="self">
    </editTemplateDialog>
    <batchUpdateValueDialog
      :dialogInfo="batchUpdateValueDialogInfo"
      @baseMounted="baseMounted"
      :self="self">
    </batchUpdateValueDialog>
</template>

<script>

import { ref, unref, watch, onMounted } from 'vue'
import { post } from "/src/api/index";
import batchUpdateValueDialog from '../edit_dialog.vue'
import editTemplateDialog from '../edit_dialog.vue'
import { ElMessage } from '/src/utils'
import { sdp_language, sdp_language_block_common, sdp_language_sql_extra_info } from '/src/utils'
import { ElMessageBox } from 'element-plus'
import * as monaco from "monaco-editor";

export default {
    emits: ['baseMounted'],
    components:{
      editTemplateDialog,
      batchUpdateValueDialog,
    },
    props: {
      self:{},
    },
    setup(prop,context) {

        const editTemplateDialogInfo = ref({
          title: '编辑模板',
          visible:false,
          tip: '在标记字符后按Ctrl键，可进行语法提示，例如{、*、&、=',
          destroyOnClose: true,
          width:'95vw',
          loading: false,
          rules:[],
          form:{},
          form_ori: {},
          editor: {
            theme: 'vs-dark',
            editor: null,
            language: 'sdp',
            value: ref(null),
            options: {
              colorDecorators: true,
              lineHeight: 24,
              tabSize: 2,
              autoClosingDelete: 'never',
            },
          },
          columns:[
            {
              prop: 'file_template',
              label: '模板',
              type: 'monaco-editor',
              labelVisible: false,
            },
          ],
          onconfirm: (param) => {
            const {dialogInfo} = param
            if (dialogInfo.is_diff) {
              dialogInfo.hide(param)
              return;
            }
            let form = prop.self.getFormAndcheckRequired(dialogInfo)
            if (!form) {
              return;
            }
            if (form.file_template == unref(editTemplateDialogInfo).form_ori.file_template) {
              ElMessage.error('未修改内容');
              return;
            }

            dialogInfo.loading = true
            post('sdp_template', 'update', {id: form.id, file_template: form.file_template})
            .then( data => {
              if (data >= 0) {
                ElMessage.success(`成功`);
                prop.self.handleSearch()
                dialogInfo.loading = false
                unref(editTemplateDialogInfo).form_ori.file_template = form.file_template
                dialogInfo.hide(param)
              } else {
                ElMessage.error(`失败:${data}`);
                dialogInfo.loading = false
              }
            })
            .catch(err => {
              console.error('ex', ex)
              ElMessage.error(`失败:${err}`, err);
              dialogInfo.loading = false
            })
          },
          hide: (param) => {

            const {dialogInfo} = param
            if (dialogInfo.form.file_template != dialogInfo.form_ori.file_template) {
              ElMessage.error('已经修改内容，不可直接关闭，可以点击右上角关闭图标强制关闭对话框');
              return;
            }
            if (dialogInfo.form.file_template_update && dialogInfo.form.file_template_update != dialogInfo.form_ori.file_template) {
              ElMessage.error('当前工程文件已经修改内容，不可直接关闭，可以点击右上角关闭图标强制关闭对话框');
              return;
            }
            if (dialogInfo.form.file_template_new_update && dialogInfo.form.file_template_new_update != dialogInfo.form_ori.file_template_new) {
              ElMessage.error('其他工程文件已经修改内容，不可直接关闭，可以点击右上角关闭图标强制关闭对话框');
              return;
            }
            dialogInfo.form = {}
            dialogInfo.visible = false
            dialogInfo.loading = false
          },
          show: (param) => {
            let {dialogInfo, query, selectRows} = param
            if (!selectRows || selectRows.length == 0) {
              ElMessage.error(`请选择一条记录后再操作`);
              return;
            }
            dialogInfo.form_ori = {...selectRows[0]}
            dialogInfo.form = {...selectRows[0]}
            post('sdp_workspace_config', 'list', {workspace_name: dialogInfo.form.workspace_name})
            .then( data => {
              dialogInfo.sdp_workspace_config = data

              dialogInfo.columns.forEach( item => {
                if (item.oninit) {
                  item.oninit({...self, mode: 'init', dialogInfo:dialogInfo, column:item, columns: dialogInfo.columns, form: dialogInfo.form})
                }
              })
              dialogInfo.buttons.forEach( item => {
                if (item.prop.indexOf('write') >= 0) {
                  if (dialogInfo.is_diff) {
                    item.hide = false
                  } else {
                    item.hide = true
                  }
                }
              })

              dialogInfo.visible = true
              setTimeout(unref(editTemplateDialogInfo).initMonaco, 100)
            })

          },
          initMonacoOnce: () => {

            let dialogInfo = prop.self.editTemplateDialogInfo
            let keywords = {}
            for(let p in sdp_language) {
              sdp_language[p].forEach(ele => {
                keywords[ele.prop] = 1
                Array.from(ele.props || []).forEach( ele => {
                  keywords[ele.prop] = 1
                })
              })
            }
            dialogInfo.sdp_workspace_config.forEach( ele => {
              keywords[ele.name] = 1
            })
            sdp_language_block_common.forEach ( ele => {
              keywords[ele.prop] = 1
            })

            if (!window.sdp_language_regitered) {
              window.sdp_language_regitered = true

              monaco.languages.register({ id: 'sdp' });
              monaco.languages.registerCompletionItemProvider('sdp', {
                triggerCharacters: ['{'],
                provideCompletionItems (model, position) {
                  const { lineNumber, column } = position
                  // 光标前文本
                  let textBeforePointer = model.getValueInRange({
                    startLineNumber: lineNumber,
                    startColumn: 0,
                    endLineNumber: lineNumber,
                    endColumn: column
                  })
                  let suggestionIndex = 100
                  let suggestions = []

                  if(textBeforePointer.substring(textBeforePointer.length - 2) == '{*'){
                    suggestions = sdp_language.blocks.map ( ele => ({
                      label: (ele.suggestion || ele.prop) + ' ' + ele.label,
                      insertText: (ele.suggestion || ele.prop),
                      sortText: (suggestionIndex++)+'s'
                    }))
                    return {suggestions}
                  }
                  if(textBeforePointer.substring(textBeforePointer.length - 1) == '{'){
                    suggestions = sdp_language.keys.map ( ele => ({
                      label: (ele.suggestion || ele.prop) + ' ' + ele.label,
                      insertText: (ele.suggestion || ele.prop),
                      sortText: (suggestionIndex++)+'s'
                    }))
                    return { suggestions }
                  }
                  if(textBeforePointer.substring(textBeforePointer.length - 1) == '&'){
                    let index = textBeforePointer.lastIndexOf('{')
                    if (index < 0) {
                      return null;
                    }
                    textBeforePointer = textBeforePointer.substring(index+1)
                    textBeforePointer = textBeforePointer.substring(0, textBeforePointer.indexOf('&'))
                    if (textBeforePointer == '' || textBeforePointer == '*') {
                      return null;
                    }
                    let subs
                    if (textBeforePointer.substring(0, 1) == '*') {
                      textBeforePointer = textBeforePointer.substring(1)
                      subs = sdp_language.blocks
                    } else {
                      subs = sdp_language.keys
                    }
                    if (subs) {
                      let ele = subs.find(ele => textBeforePointer == ele.prop)
                      if (ele && ele.props) {
                        ele.props.map(ele => {
                          suggestions.push({
                            label: (ele.suggestion || ele.prop)+ ' ' + ele.label,
                            insertText: (ele.suggestion || ele.prop),
                            sortText: (suggestionIndex++)+'s'
                          })
                        })
                        return {suggestions}
                      }
                      
                      return null;
                    }
                    return null;
                  }
                  if(textBeforePointer.substring(textBeforePointer.length - 1) == '='){
                    let index = textBeforePointer.lastIndexOf('&')
                    if (index < 0) {
                      return null;
                    }
                    let propName = textBeforePointer.substring(index+1)
                    propName = propName.substring(0, propName.indexOf('='))
                    if (propName == '' || propName == '*') {
                      return null;
                    }
                    index = textBeforePointer.lastIndexOf('{')
                    if (index < 0) {
                      return null;
                    }
                    textBeforePointer = textBeforePointer.substring(index+1)
                    textBeforePointer = textBeforePointer.substring(0, textBeforePointer.indexOf('&'))
                    if (textBeforePointer == '' || textBeforePointer == '*') {
                      return null;
                    }
                    if (textBeforePointer.substring(0, 1) == '*') {
                      textBeforePointer = textBeforePointer.substring(1)
                      let ele = sdp_language.blocks.find(ele => textBeforePointer == ele.prop)
                      if (ele) {
                        if ( (propName == 'extra_request_columns' || propName == 'extra_response_columns') && textBeforePointer == 'columns') {
                          [
                            {
                              label: 'add 新增',
                              insertText: 'add',
                              sortText: (suggestionIndex++)+'s'
                            },
                            {
                              label: 'delete 删除',
                              insertText: 'delete',
                              sortText: (suggestionIndex++)+'s'
                            },
                            {
                              label: 'update 更新',
                              insertText: 'update',
                              sortText: (suggestionIndex++)+'s'
                            },
                            {
                              label: 'query 查询',
                              insertText: 'query',
                              sortText: (suggestionIndex++)+'s'
                            },
                          ].map(ele => suggestions.push(ele))
                          return {suggestions}
                        }
                      }
                      
                      return null;
                    }

                    let ele = sdp_language.keys.find( ele => textBeforePointer == ele.prop)
                    if (ele) {
                      if ( propName == 'name' && textBeforePointer == 'config') {
                        let dialogInfo = prop.self.editTemplateDialogInfo
                        dialogInfo.sdp_workspace_config.map( ele => {
                          suggestions.push({
                            label: ele.name + ' ' + (ele.remark || '') + '(' + (ele.value || '') + ')',
                            insertText: ele.name,
                            sortText: (suggestionIndex++)+'s'
                          })
                        })
                        return {suggestions}
                      }
                      if ( (propName == 'is_rename' || propName == 'is_replace') && textBeforePointer == 'column_name') {
                        sdp_language_sql_extra_info.map( ele => {
                          suggestions.push({
                            label: (ele.suggestion || ele.prop) + ' ' + ele.label,
                            insertText: (ele.suggestion || ele.prop),
                            sortText: (suggestionIndex++)+'s'
                          })
                        })
                        return {suggestions}
                      }
                      
                    }
                    return null;
                  }
                }
              });
            }

            monaco.languages.setMonarchTokensProvider('sdp', {
              wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
              comments: {
                  lineComment: '//',
                  blockComment: ['/*', '*/']
              },
              // brackets: [
              //     ['{', '}'],
              //     ['[', ']'],
              //     ['(', ')']
              // ],
              autoClosingPairs: [
                  { open: '{', close: '}' },
                  { open: '[', close: ']' },
                  { open: '(', close: ')' },
                  { open: '"', close: '"' },
                  { open: "'", close: "'" }
              ],
              surroundingPairs: [
                  { open: '{', close: '}' },
                  { open: '[', close: ']' },
                  { open: '(', close: ')' },
                  { open: '"', close: '"' },
                  { open: "'", close: "'" },
                  { open: '<', close: '>' }
              ],
              folding: {
                  markers: {
                      start: new RegExp('^\\s*//\\s*(?:(?:#?region\\b)|(?:<editor-fold\\b))'),
                      end: new RegExp('^\\s*//\\s*(?:(?:#?endregion\\b)|(?:</editor-fold>))')
                  }
              },
              defaultToken: '',
              tokenPostfix: '.java',
              keywords: [
                  ...Object.keys(keywords),
                  ...(sdp_language_sql_extra_info.map(ele => ele.prop)),
                  'add',
                  'delete',
                  'update',
                  'query',
                  
                  'abstract',
                  'continue',
                  'for',
                  'new',
                  'switch',
                  'assert',
                  'default',
                  'goto',
                  'package',
                  'synchronized',
                  'boolean',
                  'do',
                  'if',
                  'private',
                  'this',
                  'break',
                  'double',
                  'implements',
                  'protected',
                  'throw',
                  'byte',
                  'else',
                  'import',
                  'public',
                  'throws',
                  'case',
                  'enum',
                  'instanceof',
                  'return',
                  'transient',
                  'catch',
                  'extends',
                  'int',
                  'short',
                  'try',
                  'char',
                  'final',
                  'interface',
                  'static',
                  'void',
                  'class',
                  'finally',
                  'long',
                  'strictfp',
                  'volatile',
                  'const',
                  'float',
                  'native',
                  'super',
                  'while',
                  'true',
                  'false'
              ],
              operators: [
                  '=',
                  '>',
                  '<',
                  '!',
                  '~',
                  '?',
                  ':',
                  '==',
                  '<=',
                  '>=',
                  '!=',
                  '&&',
                  '||',
                  '++',
                  '--',
                  '+',
                  '-',
                  '*',
                  '/',
                  '&',
                  '|',
                  '^',
                  '%',
                  '<<',
                  '>>',
                  '>>>',
                  '+=',
                  '-=',
                  '*=',
                  '/=',
                  '&=',
                  '|=',
                  '^=',
                  '%=',
                  '<<=',
                  '>>=',
                  '>>>='
              ],
              // we include these common regular expressions
              symbols: /[=><!~?:&|+\-*\/\^%]+/,
              escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
              digits: /\d+(_+\d+)*/,
              octaldigits: /[0-7]+(_+[0-7]+)*/,
              binarydigits: /[0-1]+(_+[0-1]+)*/,
              hexdigits: /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,
              // The main tokenizer for our languages
              tokenizer: {
                  root: [
                      // identifiers and keywords
                      [
                          /[a-zA-Z_$][\w$]*/,
                          {
                              cases: {
                                  '@keywords': { token: 'keyword.$0' },
                                  '@default': 'identifier'
                              }
                          }
                      ],
                      // whitespace
                      { include: '@whitespace' },
                      // delimiters and operators
                      [/[{}()\[\]]/, '@brackets'],
                      [/[<>](?!@symbols)/, '@brackets'],
                      [
                          /@symbols/,
                          {
                              cases: {
                                  '@operators': 'delimiter',
                                  '@default': ''
                              }
                          }
                      ],
                      // @ annotations.
                      [/@\s*[a-zA-Z_\$][\w\$]*/, 'annotation'],
                      // numbers
                      [/(@digits)[eE]([\-+]?(@digits))?[fFdD]?/, 'number.float'],
                      [/(@digits)\.(@digits)([eE][\-+]?(@digits))?[fFdD]?/, 'number.float'],
                      [/0[xX](@hexdigits)[Ll]?/, 'number.hex'],
                      [/0(@octaldigits)[Ll]?/, 'number.octal'],
                      [/0[bB](@binarydigits)[Ll]?/, 'number.binary'],
                      [/(@digits)[fFdD]/, 'number.float'],
                      [/(@digits)[lL]?/, 'number'],
                      // delimiter: after number because of .\d floats
                      [/[;,.]/, 'delimiter'],
                      // strings
                      [/""([^"\\]|\\.)*$/, 'string.invalid'],
                      [/""/, 'string', '@string'],
                      // characters
                      [/''[^\\']'/, 'string'],
                      [/('')(@escapes)(')/, ['string', 'string.escape', 'string']],
                      [/''/, 'string.invalid']
                  ],
                  whitespace: [
                      [/[ \t\r\n]+/, ''],
                      [/c\/\*\*(?!\/)/, 'comment.doc', '@javadoc'],
                      [/c\/\*/, 'comment', '@comment'],
                      [/c\/\/.*$/, 'comment']
                  ],
                  comment: [
                      [/[^c\/*]+/, 'comment'],
                      // [/\/\*/, 'comment', '@push' ],    // nested comment not allowed :-(
                      // [/\/\*/,    'comment.invalid' ],    // this breaks block comments in the shape of /* //*/
                      [/c\*\//, 'comment', '@pop'],
                      [/[c\/*]/, 'comment']
                  ],
                  //Identical copy of comment above, except for the addition of .doc
                  javadoc: [
                      [/[^c\/*]+/, 'comment.doc'],
                      // [/\/\*/, 'comment.doc', '@push' ],    // nested comment not allowed :-(
                      [/c\/\*/, 'comment.doc.invalid'],
                      [/c\*\//, 'comment.doc', '@pop'],
                      [/[c\/*]/, 'comment.doc']
                  ],
                  string: [
                      [/[^\\"\\"]+/, 'string'],
                      [/@escapes/, 'string.escape'],
                      [/\\./, 'string.escape.invalid'],
                      [/""/, 'string', '@pop']
                  ]
              }
            });
          },
          initMonaco: () => {
            let editorDomParent = document.getElementById("monaco-editor-parent");
            editorDomParent.removeChild(editorDomParent.children[0])
            let editorDom = document.createElement('div')
            editorDom.setAttribute('class', 'monaco-editor')
            editorDom.setAttribute('id', 'monaco-editor')
            editorDom.style.height= '80vh'
            editorDomParent.appendChild(editorDom)
            
            let dialogInfo = unref(editTemplateDialogInfo)

            window.addEventListener('keydown',dialogInfo.handleKeydown)
            window.addEventListener('keyup',dialogInfo.handleKeyup)
            dialogInfo.initMonacoOnce()
            
            dialogInfo.editor.value = dialogInfo.form.file_template

            let editor
            if (dialogInfo.is_diff) {
              editor = monaco.editor.createDiffEditor(editorDom, {
                minimap: { enabled: false }, // 小地图
                automaticLayout: true, // 自动布局,
                codeLens: true,
                colorDecorators: true,
                contextmenu: true,
                readOnly: false, //是否只读
                originalEditable: true,
                formatOnPaste: false,
                overviewRulerBorder: false, // 滚动条的边框
                scrollBeyondLastLine: true,
                mouseWheelZoom: true,
                theme: 'vs', // 主题
                fontSize: 12, // 字体
              });
              editor.setModel({
                original: monaco.editor.createModel(dialogInfo.form.file_template, 'sdp'),
                modified: monaco.editor.createModel(dialogInfo.form.file_template_new, 'sdp'),
              });
              let originalEditor = editor.getOriginalEditor();
              let modifiedEditor = editor.getModifiedEditor();

              let modifyContent = (selectionEditor, srcEditor, destEditor) => {
                let selection = selectionEditor.getSelection()
                  let startLineNumber = selection.startLineNumber
                  let endLineNumber = selection.endLineNumber + 1
                  let srcModel = srcEditor.getModel();
                  let destModel = destEditor.getModel()
                  for(let pos = startLineNumber; pos < endLineNumber; pos++) {
                    let line = srcModel.getLineContent(pos)
                    destModel.applyEdits([{
                      range: {
                        startColumn: 0, startLineNumber: pos, endColumn: 10000, endLineNumber: pos,
                      },
                      text: line
                    }], true)
                  }
              }

              originalEditor.addAction({
                id:'originalEditor-use-this',
                label: 'use this lines',
                precondition: null,
                keybindingContext: null,
                contextMenuGroupId: 'navigation',
                contextMenuOrder: 1,
                run: (param) => {
                  modifyContent(originalEditor, originalEditor, modifiedEditor)
                }
              })
              originalEditor.addAction({
                id:'originalEditor-use-other',
                label: 'use other lines',
                precondition: null,
                keybindingContext: null,
                contextMenuGroupId: 'navigation',
                contextMenuOrder: 1.1,
                run: (param) => {
                  modifyContent(originalEditor, modifiedEditor, originalEditor)
                }
              })
              modifiedEditor.addAction({
                id:'modifiedEditor-use-this',
                label: 'use this lines',
                precondition: null,
                keybindingContext: null,
                contextMenuGroupId: 'navigation',
                contextMenuOrder: 1,
                run: (param) => {
                  modifyContent(modifiedEditor, modifiedEditor, originalEditor)
                }
              })
              modifiedEditor.addAction({
                id:'modifiedEditor-use-other',
                label: 'use other lines',
                precondition: null,
                keybindingContext: null,
                contextMenuGroupId: 'navigation',
                contextMenuOrder: 1.1,
                run: (param) => {
                  modifyContent(modifiedEditor, originalEditor, modifiedEditor)
                }
              })
              editor.onDidUpdateDiff( () => {
                dialogInfo.form.file_template_update = originalEditor.getValue()
                dialogInfo.form.file_template_new_update = modifiedEditor.getValue()
              })

            } else {
              editor = monaco.editor.create(editorDom, {
                value: dialogInfo.editor.value,
                language: 'sdp',
                theme: 'vs-dark',
                minimap: { enabled: false }, // 小地图
                options: {
                  colorDecorators: true,
                  lineHeight: 24,
                  tabSize: 2,
                  autoClosingDelete: 'never',
                },
              });
              editor.onDidChangeModelContent((e,b,c) => { // 监听修改
                dialogInfo.form.file_template = editor.getValue()
              })
            }

            dialogInfo.editor.editor = editor

          },

          handleKeydown:(event) => {
            let dialogInfo = unref(editTemplateDialogInfo)

            if (!dialogInfo.is_diff) {
              if (event.key == 'Control') {
                dialogInfo.is_control_down = true;
              } else {
                dialogInfo.is_control_down = false;
              }
            }
          },
          handleKeyup:(event) => {
            let dialogInfo = unref(editTemplateDialogInfo)

            if (!dialogInfo.is_diff) {
              if (event.key == 'Control') {
                if (dialogInfo.is_control_down) {
                  let editor = dialogInfo.editor.editor
                  editor.trigger('{', 'editor.action.triggerSuggest', {});
                  dialogInfo.is_control_down = false;
                }
              } else {
                dialogInfo.is_control_down = false;
              }
            }
          },
          buttons: [
          {
              prop: 'writeCurrent',
              label: '保存当前工作区文件',
              hide: true,
              onclick: (param) => {
                let { button } = param
                let dialogInfo = unref(editTemplateDialogInfo)
                let form = dialogInfo.form
                let form_ori = dialogInfo.form_ori
                if (form.file_template_update == form.file_template) {
                  ElMessage.error('未改动任何内容')
                  return;
                }
                ElMessageBox.confirm('是否要保存当前工作区文件？', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  closeOnClickModal: false,
                  type: 'warning',
                })
                  .then(() => {
                    button.loading = true
                    post('sdp_template', 'update', {id:form.id, file_template: form.file_template_update})
                    .then((data) => {
                      form.file_template = form.file_template_update
                      form_ori.file_template = form.file_template_update
                      form.file_template_update = ''
                      form_ori.file_template_update = ''
                      ElMessage.success(`操作成功`);
                      button.loading = false;
                      let item = unref(prop.self.tableData).find(ele => ele.id == form.id)
                      item.file_template = form.file_template
                      item.name_diff = item.name_diff.replace('不一致', '已处理')
                    })
                    .catch(ex => {
                      console.error('ex', ex)
                      ElMessage.error(`操作失败`);
                      button.loading = false;
                    })
                  })
              }
            },
            {
              prop: 'writeOther',
              label: '保存其他工作区文件',
              hide: true,
              onclick: (param) => {
                let { button } = param
                let dialogInfo = unref(editTemplateDialogInfo)
                let form = dialogInfo.form
                let form_ori = dialogInfo.form_ori
                if (form.file_template_new_update == form.file_template_new) {
                  ElMessage.error('未改动任何内容')
                  return;
                }
                ElMessageBox.confirm('是否要保存其他工作区文件？', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  closeOnClickModal: false,
                  type: 'warning',
                })
                  .then(() => {
                    button.loading = true
                    post('sdp_template', 'update', {id:form.id_new, file_template: form.file_template_new_update})
                    .then((data) => {
                      form.file_template_new = form.file_template_new_update
                      form_ori.file_template_new = form.file_template_new_update
                      form.file_template_new_update = ''
                      form_ori.file_template_new_update = ''
                      ElMessage.success(`操作成功`);
                      button.loading = false;
                      let item = unref(prop.self.tableData).find(ele => ele.id == form.id)
                      item.file_template_new = form.file_template_new
                      item.name_diff = item.name_diff.replace('不一致', '已处理')
                    })
                    .catch(ex => {
                      console.error('ex, ex')
                      ElMessage.error(`操作失败`);
                      button.loading = false;
                    })
                  })
              }
            },
            {
              prop: 'overwriteCurrent',
              label: '覆盖当前工作区文件',
              hide: true,
              onclick: (param) => {
                let { button } = param
                ElMessageBox.confirm('是否要覆盖当前工作区文件？', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  closeOnClickModal: false,
                  type: 'warning',
                })
                  .then(() => {
                    let dialogInfo = unref(editTemplateDialogInfo)
                    let form = dialogInfo.form
                    let form_ori = dialogInfo.form_ori
                    button.loading = true
                    post('sdp_template', 'update', {id:form.id, file_template: form.file_template_new})
                    .then((data) => {
                      form.file_template = form.file_template_new
                      form_ori.file_template = form.file_template_new
                      form.file_template_update = form.file_template_new
                      form_ori.file_template_update = form.file_template_new
                      ElMessage.success(`操作成功`);
                      button.loading = false;
                      let item = unref(prop.self.tableData).find(ele => ele.id == form.id)
                      item.file_template = form.file_template_new
                      item.name_diff = item.name_diff.replace('不一致', '已处理')
                      dialogInfo.hide({dialogInfo})
                    })
                    .catch(ex => {
                      console.error('ex', ex)
                      ElMessage.error(`操作失败`);
                      button.loading = false;
                    })
                  })
              }
            },
            {
              prop: 'overwriteOther',
              label: '覆盖其他工作区文件',
              hide: true,
              onclick: (param) => {
                let { button } = param
                ElMessageBox.confirm('是否要覆盖其他工作区文件？', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  closeOnClickModal: false,
                  type: 'warning',
                })
                  .then(() => {
                    let dialogInfo = unref(editTemplateDialogInfo)
                    let form = dialogInfo.form
                    let form_ori = dialogInfo.form_ori
                    button.loading = true
                    post('sdp_template', 'update', {id:form.id_new, file_template: form.file_template})
                    .then((data) => {
                      form.file_template_new = form.file_template
                      form_ori.file_template_new = form.file_template
                      form.file_template_new_update = form.file_template
                      form_ori.file_template_new_update = form.file_template
                      ElMessage.success(`操作成功`);
                      button.loading = false;
                      let item = unref(prop.self.tableData).find(ele => ele.id == form.id)
                      item.file_template_new = form.file_template
                      item.name_diff = item.name_diff.replace('不一致', '已处理')
                      dialogInfo.hide({dialogInfo})
                    })
                    .catch(ex => {
                      console.error('ex', ex)
                      ElMessage.error(`操作失败`);
                      button.loading = false;
                    })
                  })
              }
            },
          ]

        })
        prop.self.init_remote_list(editTemplateDialogInfo.value.columns, { query: unref(editTemplateDialogInfo).form})
        prop.self.editTemplateDialogInfo = editTemplateDialogInfo

        editTemplateDialogInfo.value.columns.forEach( item => {
          if (item.oninit) {
            item.oninit({...self,
              mode: 'init',
              dialogInfo: editTemplateDialogInfo.value,
              column:item,
              columns: editTemplateDialogInfo.value.columns,
              form: editTemplateDialogInfo.value.form})
          }
        })

        const baseMounted = (v) => {
        }

        return {
          editTemplateDialogInfo,
          batchUpdateValueDialogInfo: prop.self.batchUpdateValueDialogInfo,
          baseMounted,
        };
    },
};
</script>

<style scoped>
</style>
